package com.yumingjaing.thread;

/**
 * @description: 测试获取到锁后调用sleep会释放锁的场景
 * @author: John
 * @version: ThreadSyncSleepTest.java, v1.0 2024年12月15日 05:58
 */
public class ThreadSyncSleepTest {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(ThreadSyncSleepTest::sync,"t1");
        Thread t2 = new Thread(ThreadSyncSleepTest::sync,"t2");
        t1.start();
        t2.start();
        Thread.sleep(30);
        synchronized (ThreadSyncSleepTest.class) {
            ThreadSyncSleepTest.class.notifyAll();
        }
        Thread.sleep(6);
        System.out.println("t1:"+t1.getState());
        System.out.println("t2:"+t2.getState());
    }


    public static synchronized void sync()  {
        try {
            for (int i = 0; i < 10; i++) {
                if(i == 5) {
                    ThreadSyncSleepTest.class.wait();//这里会释放掉自己本身持有的锁
                }
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}